<?php

namespace app\stores\model\cash;

use app\beautiful\model\mall\GoodsModel;
use app\common\model\CommonModel;
use app\common\model\ProduceDepartModel;
use think\facade\Db;


class CashCategoryModel extends CommonModel{

    protected  $name = 'beautiful_cash_category';

    protected  $pk   = 'category_id';
    /**
     * 模型写入前事件（钩子函数）
     */
    public static function onBeforeInsert($model)
    {
        $model->set("add_time", date('Y-m-d H:i:s'));
        $model->set("edit_time", date('Y-m-d H:i:s'));
        $model->set("add_ip", request()->ip());
    }
    public static function info($where,$field='*')
    {
        $list = Db::name('beautiful_cash_category')->where($where)->field($field)->find();

        return $list;
    }
    public static function up($data,$where){
        $data['edit_time']=date('Y-m-d H:i:s');
        $res=self::update($data,$where);
        return $res;
    }
    public static function list($where,$order,$page=0,$limit=0){
        $query = Db::name('beautiful_cash_category')
            ->when(isset($where['shop_id']) && !empty($where['shop_id']),function ($query) use ($where){
                $query->where('shop_id','=',$where['shop_id']);
            })->when(isset($where['type']) && !empty($where['type']),function ($query) use ($where){
                $query->where('type','=',$where['type']);
            })->when(isset($where['status']) && !empty($where['status']),function ($query) use ($where){
                $query->where('status','=',$where['status']);
            })
            ->where(['is_delete'=>0])
            ->field("*");
        $count = $query->count();
        $query = $query->order($order);
        if($page>0) $query = $query->page($page);
        if($limit>0) $query = $query->limit($limit);
        $list = $query->select()->toArray();
        if(!empty($list)){
            foreach ($list as $k=>$v){
                $depart = ProduceDepartModel::where(['shop_id'=>$v['shop_id'],'is_delete'=>0,'id'=>$v['produce_depart_id']])->find();
                $list[$k]['depart_name'] = $depart?$depart['name']:null;
                $list[$k]['goods_num'] = GoodsModel::where(['shop_id'=>$v['shop_id'],'is_delete'=>0,'cash_category_id'=>$v['category_id']])->count();
            }
        }
        return compact('count','list');
    }
}

